from datetime import datetime
import random
from flask import abort, jsonify, session
from flask import current_app
from flask import render_template
from flask import request
from flask import make_response
from info import constants, db
from info import redis_store
from info.models import User
from info.utils.captcha.captcha import captcha
from info.libs.yuntongxun.sms import CCP
from . import passport_blu
import re
from info.utils.response_code import RET


@passport_blu.route('/logout')
def logout():
    #  1 删除user_id
    session.pop('user_id')
    return jsonify(errno=RET.OK, errmsg='登出成功')


@passport_blu.route('/login', methods=['post'])
def login():
    args_dict = request.json
    mobile = args_dict.get('mobile')
    password = args_dict.get('password')
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    #  查询用户名和密码是否一致
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as ret:
        print(ret)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not user:
        return jsonify(errno=RET.DATAEXIST, errmsg='用户不存在')
    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg='用户名或密码错误')

    #  模板文件找的是创建app文件的同级目录templates内的文件
    session['user_id'] = user.id

    #  保存用户最后一次登陆时间
    user.last_login = datetime.now()
    try:
        db.session.commit()
    except Exception as ret:
        db.session.rollback()
        print(ret)
        return jsonify(errno=RET.DATAERR, errmsg='数据库存储错误')
    return jsonify(errno=RET.OK, errmsg='登陆成功')


@passport_blu.route('/register',methods=['post'])
def register():
    #  1.获取传入的数据
    agr_dict = request.json
    mobile= agr_dict.get('mobile')
    #  手机验证码
    smscode = agr_dict.get('smscode')
    #  密码 passport
    password = agr_dict.get('password')
    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    try:
        real_smscode = redis_store.get('sms_'+mobile)
    except Exception as ret:
        print(ret)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not real_smscode:
        return jsonify(errno=RET.NODATA, errmsg='验证码过期')
    if real_smscode != smscode:
        return jsonify(errno=RET.DATAERR, errmsg='验证码错误')
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as ret:
        print(ret)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='手机号码以存在')

    user = User()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = password

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as ret:
        print(ret)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg='数据库存储错误')
    #  存储user_id到redis中表示用户登陆状态
    session['user_id'] = user.id

    return jsonify(errno=RET.OK, errmsg='注册成功')


@passport_blu.route('/sms_code', methods=['post'])
def send_sms():
    print('进入发送验证码函数')
    #  1.获取传入的数据
    agr_dict = request.json
    #  手机号码 mobile
    mobile = agr_dict.get('mobile')
    #  验证码内容 image_code
    image_code = agr_dict.get('image_code')
    #  验证码随机数 image_code_id
    image_code_id = agr_dict.get('image_code_id')
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数有误')

    # 2. 验证手机号码是否正确
    if not re.match(r'^1[3578][0-9]{9}$', mobile):
        print(mobile)
        return jsonify(errno=RET.PARAMERR, errmsg='手机格式不正确')

    # 3. 判断验证码是否输入正确
    try:
        real_image_code = redis_store.get('imagecode'+image_code_id)
        print(real_image_code)
    except Exception as ret:
        print(ret)
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 4.判断验证码是否过期
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg='图片验证码过期')

    if real_image_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg='图片验证码错误')
    # 5.生成随机验证码
    r_str = '06%d' % random.randint(0, 99999)
    try:
        redis_store.set('sms_'+mobile, r_str, constants.SMS_CODE_REDIS_EXPIRES//5)
    except Exception as ret:
        print(ret)
        return jsonify(errno=RET.DATAERR, errmsg='数据库错误')

    current_app.logger.debug('手机验证码是{}'.format(r_str))
    result = CCP().send_template_sms(mobile, [r_str, 1], 1)
    if result != 0:
        return jsonify(errno=RET.THIRDERR, errmsg='发送短信验证码失败')

    return jsonify(errno=RET.OK, errmsg='发送成功')


@passport_blu.route('/image_code')
def get_image_code():
    #  获取唯一的随机值
    uni_num = request.args.get('imagecode')
    if not uni_num:
        abort(403)
    name, text, image = captcha.generate_captcha()
    try:
        redis_store.set('imagecode'+uni_num, text, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as ret:
        print(ret)
        abort(500)
        current_app.logger.error('数据库存储错误')
    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpg'
    print('图片验证码是',text)
    return response


